package com.woniuxy.redenvelope.listener;

import com.woniuxy.redenvelope.mapper.KillRedEnvelopeMapper;
import com.woniuxy.redenvelope.mapper.RecordMapper;
import com.woniuxy.redenvelope.util.RedisKeyExpireUtil;
import com.woniuxy.redenvelope.vo.AddKillVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.nio.charset.StandardCharsets;

@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Resource
    private RedisKeyExpireUtil redisKeyExpireUtil;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private KillRedEnvelopeMapper killRedEnvelopeMapper;

    @Resource
    private RecordMapper recordMapper;

    // 配置监听哪个频道
    private static final Topic KEYEVENT_EXPIRED_TOPIC = new PatternTopic("__keyevent@0__:expired");

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    protected void doRegister(RedisMessageListenerContainer listenerContainer) {
        // 频道可以是多个，多个传list
        listenerContainer.addMessageListener(this, KEYEVENT_EXPIRED_TOPIC);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = new String(message.getBody(), StandardCharsets.UTF_8);

        System.out.println("监听到失效的key：" + expiredKey);

        if (expiredKey.startsWith("kill_start_")) {
            int kid = Integer.parseInt(expiredKey.split("_")[2]);
            log.info("处理秒杀开始，秒杀ID: {}", kid);
            // 拿到该kid的秒杀信息
            redisTemplate.getExpire("kill_start_" + kid);
            killRedEnvelopeMapper.updateStatus(kid, "进行中");
            redisKeyExpireUtil.addKill(kid);
        }

        // 处理秒杀结束
        if (expiredKey.startsWith("kill_end_")) {
            int kid = Integer.parseInt(expiredKey.split("_")[2]);
            log.info("处理秒杀结束，秒杀ID: {}", kid);
            killRedEnvelopeMapper.updateStatus(kid, "已结束");
            redisKeyExpireUtil.removeKill(kid);
        }

        if (expiredKey.startsWith("redtime_")) {
            int pid = Integer.parseInt(expiredKey.split("_")[1]);
            log.info("处理过期红包，红包ID: {}", pid);
            // 拿到该kid的秒杀信息
            recordMapper.updateStatus(pid, "已过期");
        }
    }
}